#include "commodityinformation.h"
#include "ui_commodityinformation.h"
#include "categorysettings.h"
#include <QDebug>
#include "inquiresql.h"
#include "addmodifycommodity.h"
#include <QMessageBox>
#include "attributesetting.h"

#include <QDesktopWidget>

CommodityInformation::CommodityInformation(QWidget *parent) :
    QWidget(parent), ui(new Ui::CommodityInformation)
{
    ui->setupUi(this);
    this->setLayout(ui->MainLayout);

    m_categorysettings = NULL;

    //设置自定义的鼠标指针图案
    QCursor *myCursor= new QCursor(QPixmap(":/Mouse/Image/mouse/mouse.png"),15,10);
    setCursor(*myCursor);

    m_sql = new InquireSql;
    m_addModifyCommodity = new AddModifyCommodity(this);
    m_attributeSetting = new AttributeSetting(this);

    m_addModifyCommodity->hide();
    m_attributeSetting->hide();

    //设置列宽可拖动
//    ui->tableWidgetCommodityInformation->horizontalHeader()->setResizeMode(QHeaderView::Interactive);
//    ui->tableWidgetCommodityInformation->verticalHeader()->setResizeMode(QHeaderView::Interactive);

    QHeaderView* vheaderView = ui->tableWidgetCommodityInformation->verticalHeader();
    vheaderView->setHidden(true);

    displayCommodityInformation("all");

    connect(m_addModifyCommodity, SIGNAL(displayCommodityInformation()),
            this, SLOT(slotDisplayCommodityInformation()));
    connect(m_addModifyCommodity, SIGNAL(signalDisplayAttributeSettings(int)),
            this, SLOT(on_comboBoxOtherSettings_currentIndexChanged(int)));
    connect(m_attributeSetting, SIGNAL(signalUpdateComboBoxAttribute(int)),
            this, SLOT(slotUpdateAddModifyCommodity(int)));
}

CommodityInformation::~CommodityInformation()
{
    delete ui;
}

void CommodityInformation::displayCommodityInformation(const QString &inquireInformation)
{
    m_list.clear();
    m_list = m_sql->InquireCommodityInformation();
    ui->tableWidgetCommodityInformation->clear();

    QStringList headers;
    headers << tr("商品编码") << tr("商品名称") << tr("商品内码") << tr("类别") << tr("规格") << tr("颜色")
            << tr("单位") << tr("折扣") << tr("成本价") << tr("零售价") << tr("会员价") << tr("库存数量")
            << tr("最小库存") << tr("品牌") << tr("保质期") << tr("备注");

    ui->tableWidgetCommodityInformation->setColumnCount(16);
    ui->tableWidgetCommodityInformation->setHorizontalHeaderLabels(headers);

    //判断需要显示的商品信息的行数
    int RowCount = 0;
    if (inquireInformation != "all")
    {
        for(int i = 0; i < m_list.count(); ++i)
        {
            if (!(m_list.at(i).get_commodityBarcode().contains(inquireInformation, Qt::CaseInsensitive)
                    || m_list.at(i).get_commodityName().contains(inquireInformation, Qt::CaseInsensitive)
                    || m_list.at(i).get_internalCode().contains(inquireInformation, Qt::CaseInsensitive)))
            {
                continue;
            }
            else
            {
                RowCount++;
            }
        }
        ui->tableWidgetCommodityInformation->setRowCount(RowCount);
        RowCount = 0;
    }
    else
    {
        ui->tableWidgetCommodityInformation->setRowCount(m_list.count());
    }


    //显示商品库存信息
    RowCount = 0;
    int StockQuantity = 0;
    double costTotal = 0;
    for(int i = 0; i < m_list.count(); ++i)
    {
        if (inquireInformation != "all")
        {
            if (!(m_list.at(i).get_commodityBarcode().contains(inquireInformation, Qt::CaseInsensitive)
                    || m_list.at(i).get_commodityName().contains(inquireInformation, Qt::CaseInsensitive)
                    || m_list.at(i).get_internalCode().contains(inquireInformation, Qt::CaseInsensitive)))
            {
                continue;
            }
        }

        QString specifications = m_sql->InquireAttributeValue(Specification,
                                                                m_list.at(i).get_specificationsNumber());
        QString category = m_sql->InquireAttributeValue(Category,
                                                                m_list.at(i).get_categoryNumber());
        QString color = m_sql->InquireAttributeValue(Color, m_list.at(i).get_colorNumber());
        QString brand = m_sql->InquireAttributeValue(Brand, m_list.at(i).get_brandNumbe());
        QString unit = m_sql->InquireAttributeValue(Unit, m_list.at(i).get_unitNumber());

        QTableWidgetItem *commodityBarcode      = new QTableWidgetItem(m_list.at(i).get_commodityBarcode());
        QTableWidgetItem *commodityName         = new QTableWidgetItem(m_list.at(i).get_commodityName());
        QTableWidgetItem *internalCode          = new QTableWidgetItem(m_list.at(i).get_internalCode());
        QTableWidgetItem *categoryNumber        = new QTableWidgetItem(category);
        QTableWidgetItem *specificationsNumber  = new QTableWidgetItem(specifications);
        QTableWidgetItem *colorNumber           = new QTableWidgetItem(color);
        QTableWidgetItem *brandNumber           = new QTableWidgetItem(brand);
        QTableWidgetItem *unitNumber            = new QTableWidgetItem(unit);
        QTableWidgetItem *discount              = new QTableWidgetItem(m_list.at(i).get_discount());
        QTableWidgetItem *shelfLife             = new QTableWidgetItem(m_list.at(i).get_shelfLife());
        QTableWidgetItem *cost                  = new QTableWidgetItem(m_list.at(i).get_cost());
        QTableWidgetItem *sellingPrice          = new QTableWidgetItem(m_list.at(i).get_sellingPrice());
        QTableWidgetItem *memberPrice           = new QTableWidgetItem(m_list.at(i).get_memberPrice());
        QTableWidgetItem *stockQuantity         = new QTableWidgetItem(m_list.at(i).get_stockQuantity());
        QTableWidgetItem *minStock              = new QTableWidgetItem(m_list.at(i).get_minStock());
        QTableWidgetItem *remark                = new QTableWidgetItem(m_list.at(i).get_remark());

        //设置对齐方式
        commodityBarcode->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        internalCode->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        categoryNumber->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        specificationsNumber->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        colorNumber->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        unitNumber->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        discount->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        stockQuantity->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        minStock->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        cost->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter );
        sellingPrice->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter );
        memberPrice->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter );

        //设置文字颜色
        stockQuantity->setTextColor(QColor(255, 0, 0));

        commodityBarcode->setFont(QFont("DejaVu Sans", 11, 2, false));
        commodityName->setFont(QFont("DejaVu Sans", 11, 2, false));
        internalCode->setFont(QFont("DejaVu Sans", 11, 2, false));
        categoryNumber->setFont(QFont("DejaVu Sans", 11, 2, false));
        specificationsNumber->setFont(QFont("DejaVu Sans", 11, 2, false));
        colorNumber->setFont(QFont("DejaVu Sans", 11, 2, false));
        unitNumber->setFont(QFont("DejaVu Sans", 11, 2, false));
        discount->setFont(QFont("DejaVu Sans", 11, 2, false));
        cost->setFont(QFont("DejaVu Sans", 11, 2, false));
        sellingPrice->setFont(QFont("DejaVu Sans", 11, 2, false));
        memberPrice->setFont(QFont("DejaVu Sans", 11, 2, false));
        stockQuantity->setFont(QFont("DejaVu Sans", 11, 2, false));
        minStock->setFont(QFont("DejaVu Sans", 11, 2, false));
        brandNumber->setFont(QFont("DejaVu Sans", 11, 2, false));
        shelfLife->setFont(QFont("DejaVu Sans", 11, 2, false));
        remark->setFont(QFont("DejaVu Sans", 11, 2, false));

        ui->tableWidgetCommodityInformation->setItem(RowCount, 0, commodityBarcode);
        ui->tableWidgetCommodityInformation->setItem(RowCount, 1, commodityName);
        ui->tableWidgetCommodityInformation->setItem(RowCount, 2, internalCode);
        ui->tableWidgetCommodityInformation->setItem(RowCount, 3, categoryNumber);
        ui->tableWidgetCommodityInformation->setItem(RowCount, 4, specificationsNumber);
        ui->tableWidgetCommodityInformation->setItem(RowCount, 5, colorNumber);
        ui->tableWidgetCommodityInformation->setItem(RowCount, 6, unitNumber);
        ui->tableWidgetCommodityInformation->setItem(RowCount, 7, discount);
        ui->tableWidgetCommodityInformation->setItem(RowCount, 8, cost);
        ui->tableWidgetCommodityInformation->setItem(RowCount, 9, sellingPrice);
        ui->tableWidgetCommodityInformation->setItem(RowCount, 10, memberPrice);
        ui->tableWidgetCommodityInformation->setItem(RowCount, 11, stockQuantity);
        ui->tableWidgetCommodityInformation->setItem(RowCount, 12, minStock);
        ui->tableWidgetCommodityInformation->setItem(RowCount, 13, brandNumber);
        ui->tableWidgetCommodityInformation->setItem(RowCount, 14, shelfLife);
        ui->tableWidgetCommodityInformation->setItem(RowCount, 15, remark);

        RowCount++;

        StockQuantity += m_list.at(i).get_stockQuantity().toInt();
        costTotal += m_list.at(i).get_cost().toDouble()
                * m_list.at(i).get_stockQuantity().toInt();
    }

    ui->tableWidgetCommodityInformation->setCurrentItem(
                ui->tableWidgetCommodityInformation->item(RowCount - 1 , 1));

    //设置与文字相匹配的单元格大小
    ui->tableWidgetCommodityInformation->resizeColumnsToContents();
    ui->tableWidgetCommodityInformation->resizeRowsToContents();

    setTableWidgetColor();

    ui->StockQuantity->setText(QString::number(StockQuantity));
    ui->TotalCost->setText(completionPrice(QString::number(costTotal)));
}

void CommodityInformation::on_pushButtonNew_clicked()
{
    m_addModifyCommodity->displayAddModifyCommodity(addCommodityPage, 0);

    m_addModifyCommodity->setWindowFlags(Qt::Dialog);
    m_addModifyCommodity->setWindowModality(Qt::ApplicationModal);//在对 QWidget 操作时，不能操作其他东西
    m_addModifyCommodity->setAttribute(Qt::WA_ShowModal, true);
    m_addModifyCommodity->move((QApplication::desktop()->width() - m_addModifyCommodity->width())/2,
               (QApplication::desktop()->height() - m_addModifyCommodity->height())/2);
    m_addModifyCommodity->show();
}

void CommodityInformation::on_pushButtonModity_clicked()
{
    int commodityBarcode = m_list.at(ui->tableWidgetCommodityInformation->currentRow())
            .get_commodityBarcode().toInt();
    m_addModifyCommodity->displayAddModifyCommodity(modifyCommodityPage, commodityBarcode);

    m_addModifyCommodity->setWindowFlags(Qt::Dialog);
    m_addModifyCommodity->setWindowModality(Qt::ApplicationModal);//在对 QWidget 操作时，不能操作其他东西
    m_addModifyCommodity->setAttribute(Qt::WA_ShowModal, true);
    m_addModifyCommodity->move((QApplication::desktop()->width() - m_addModifyCommodity->width())/2,
               (QApplication::desktop()->height() - m_addModifyCommodity->height())/2);
    m_addModifyCommodity->show();
}

void CommodityInformation::on_comboBoxOtherSettings_activated(const QString &item)
{
    if (item == tr("类别设置"))
    {
        if (m_categorysettings == NULL)
        {
            m_categorysettings = new CategorySettings(this);
        }

        m_categorysettings->setWindowFlags(Qt::Dialog);
        m_categorysettings->setWindowModality(Qt::ApplicationModal);//在对 QWidget 操作时，不能操作其他东西
        m_categorysettings->setAttribute(Qt::WA_ShowModal, true);
        m_categorysettings->move((QApplication::desktop()->width() - m_categorysettings->width())/2,
                   (QApplication::desktop()->height() - m_categorysettings->height())/2);
        m_categorysettings->showAll();
        m_categorysettings->displayCategory();
        m_categorysettings->show();
    }
}

void CommodityInformation::slotDisplayCommodityInformation()
{
    displayCommodityInformation("all");
}

void CommodityInformation::setTableWidgetColor()
{
    for (int i = 0; i < ui->tableWidgetCommodityInformation->rowCount(); ++i)
    {
        if (i % 2 == 0)
        {
            for (int j = 0; j < ui->tableWidgetCommodityInformation->columnCount(); ++j)
            {
                QTableWidgetItem *item = ui->tableWidgetCommodityInformation->item(i,j);
                if (item)
                {
                    const QColor color = QColor(252,222,156);
                    item->setBackgroundColor(color);
                }
            }
        }
    }
}

QString CommodityInformation::completionPrice(const QString &price)
{
    QString number = price;
    if (number.isEmpty() || number.toDouble() == 0)
    {
        number.append("0.00");
        return number;
    }
    if (number.contains(".", Qt::CaseInsensitive))
    {
        if (number.left(1) == ".")
        {
            number.replace(0, 1, "0.");
            return number;
        }
        if (number.right(1) == ".")
        {
            number.append("00");
            return number;
        }
        if (number.right(2).contains(".", Qt::CaseInsensitive))
        {
            number.append("0");
            return number;
        }
    }
    else
    {
        number.append(".00");
        return number;
    }

    return NULL;
}

void CommodityInformation::on_pushButtonDelete_clicked()
{
    switch(QMessageBox::question(this, tr("              ★温馨提示★"),
                          tr("\n您确定要删除当前的记录吗?删除之后将不可恢复"),
                          QMessageBox::No | QMessageBox::Yes ,QMessageBox::No))
    {
        case QMessageBox::Yes:
            m_sql->DeleteCommodityInformation(m_list
                                              .at(ui->tableWidgetCommodityInformation->currentRow())
                                              .get_commodityBarcode());
            displayCommodityInformation("all");
            break;
        case QMessageBox::No:
            break;
        default:
            break;
    }
}

void CommodityInformation::slotUpdateAddModifyCommodity(int attribute)
{
    m_addModifyCommodity->slotUpdateComboBoxAttribute(attribute);
}

void CommodityInformation::on_comboBoxOtherSettings_currentIndexChanged(int index)
{
    switch (index)
    {
        case 1:
            break;
        case 2:
            m_attributeSetting->displayAttributePage(SpecificationSetting);
            break;
        case 3:
            m_attributeSetting->displayAttributePage(BrandsSetting);
            break;
        case 4:
            m_attributeSetting->displayAttributePage(ColorSetting);
            break;
        case 5:
            m_attributeSetting->displayAttributePage(UnitSetting);
            break;
        default:
            return;
    }

    if (index != 1)
    {
        m_attributeSetting->setWindowFlags(Qt::Dialog);
        m_attributeSetting->setWindowModality(Qt::ApplicationModal);//在对 QWidget 操作时，不能操作其他东西
        m_attributeSetting->setAttribute(Qt::WA_ShowModal, true);
        m_attributeSetting->move((QApplication::desktop()->width() - m_attributeSetting->width())/2,
                   (QApplication::desktop()->height() - m_attributeSetting->height())/2);
        m_attributeSetting->show();
    }
}

void CommodityInformation::on_pushButtonInquire_clicked()
{
    displayCommodityInformation(ui->lineEditCommodity->text());
}
